<?php

namespace App\Http\Controllers\admin\defaults;

use App\Helpers\commonFuc;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

//SELECT COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT,IS_NULLABLE,TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'www.shun6.top' AND TABLE_NAME = 'sl_admin'
//这个是数据所有表和字段
class BaseController extends Controller
{
    private $tpviewhead;
    private $table;
    public $thisModel;
    public $thisRequest;
    public $isPostOrAjax;


    function __construct(Request $thisRequest,$tpviewhead,$table)
    {


        $this->table = $table;
        $this->thisModel = DB::table($table);
        $this->thisRequest = $thisRequest;
        $this->tpviewhead = $tpviewhead;
        $this->isPostOrAjax = $this->thisRequest->isMethod('post') || $this->thisRequest->ajax();


    }
    function add(){
        if( $this->isPostOrAjax){
           return $this->save();
        }
        return view($this->tpviewhead . 'add');

    }
    function edit(){
        if( $this->isPostOrAjax){
            return $this->save();
        }
        $GLOBALS['isjson'] = false;
        $data = $this->info(true);
        return view($this->tpviewhead . 'edit',['data'=>$data]);

    }
    function save()
    {

        $id = $this->thisRequest->input('id');
        $input=($this->thisRequest->all());
        $input = $this->checkTableField($input);
        if(empty($input)){
            if($this->thisRequest->ajax()){
                return commonFuc::data_reture_json([],400,'参数错误没有符合字段');
            }else{
                return '<script>alert("参数错误没有符合字段");window.history.go(-1);</script>';
            }
        }
        if($id>0){
            $data = $this->thisModel->where('id',$id)->update($input);
            if($this->thisRequest->ajax()){
                return commonFuc::data_reture_json($data,200,'修改成功');
            }else{
                return '<script>alert("修改成功");window.history.go(-1);location.reload();</script>';
            }
        }else{
            unset($input['id']);
            $data = $this->thisModel->insertGetId($input);
            if($this->thisRequest->ajax()){
                return commonFuc::data_reture_json($data,200,'新增成功');
            }else{
                return '<script>alert("新增成功");window.history.go(-1);location.reload();</script>';
            }
        }
    }
    function dele()
    {
        $id = $this->thisRequest->get('id');
        $ids = $this->thisRequest->get('ids');
        $ids = array_merge(explode(',', $id),explode(',', $ids));
        if(empty($ids)){
            if($this->thisRequest->ajax()){
                return commonFuc::data_reture_json([], 400, 'id错误');
            }else{
                return '<script>alert("id错误");window.history.go(-1);</script>';
            }
        }

        $data = $this->thisModel->whereIn('id',$ids)->delete();
        if($this->thisRequest->ajax()){

            return commonFuc::data_reture_json([], 200, '删除成功');
        }else{
            return '<script>alert("删除成功");window.history.go(-1);location.reload();</script>';
        }
    }
    function lists()
    {
        $limit = (int)$this->thisRequest->get('limit');
        $limit = $limit ? $limit : 15;

        if($this->thisRequest->ajax()){
            $data = $this->thisModel->paginate($limit);
            return commonFuc::data_reture_json($data,200,'');
        }
        $data = $this->thisModel->paginate($limit);
        return view($this->tpviewhead . 'lists',['data'=>$data]);
    }

    function info($isajax=false){
        $id = (int)$this->thisRequest->get('id');
        if($id<1){
            if($this->thisRequest->ajax() || $isajax){
                return commonFuc::data_reture_json([], 400, 'id错误');
            }else{
                return '<script>alert("id错误");window.history.go(-1);</script>';
            }
        }
        $data = $this->thisModel->find($id);
        if( $this->isPostOrAjax || $isajax){
            return commonFuc::data_reture_json($data, 200, '');
        }else{

            return view($this->tpviewhead . 'info',['data'=>$data]);
        }
    }

    /**检查数据库字段值，过滤数据库没有的字段
     * @param $data
     * @return array
     */
    function checkTableField($data){
        $fields = $this->TableFieldCache($this->table,false);
        $chdata = [];
        foreach ($fields as $field=>$fields1){
            if(isset($data[$field])){
                $chdata[$field] = $data[$field];
            }else if($fields1['isnotnull']){
                $chdata[$field] = 0;//不能为null 时直接默认值0
            }
        }
        return $chdata;
    }

    /**获取数据库 所有表字段
     * @param string $table
     * @param bool $iscache
     * @param string $db_database
     * @return array|\Illuminate\Cache\CacheManager|\Illuminate\Contracts\Foundation\Application|mixed
     * @throws \Exception
     */
    function TableFieldCache($table='',$iscache=true,$db_database=''){
        $db_database=$db_database==''?env('DB_DATABASE'):$db_database;
        $cache_key = 'TableFiedCache' . $db_database;
        if($iscache){
            $data=cache($cache_key);
            if($data){
                if($table=='') return $data;
                if(isset($data[$table])){
                    return $data[$table];
                }
            }
        }

        $data = DB::select("SELECT COLUMN_NAME as fied,DATA_TYPE as type,COLUMN_COMMENT as title,IS_NULLABLE as isnotnull,TABLE_NAME as tablename FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{$db_database}' ");
        $data = commonFuc::object_to_array($data);

        $tablefied = [];
        foreach ($data as $valuedata){
            if(!isset($tablefied[$valuedata['tablename']])) $tablefied[$valuedata['tablename']] = [];
            $valuedata['isnotnull'] = $valuedata['isnotnull'] == 'YES' ? 0 : 1;
            $valuedata['title'] = $valuedata['title']?$valuedata['title']:$valuedata['fied'];
            $tablefied[$valuedata['tablename']][$valuedata['fied']] = $valuedata;
        }

        cache($cache_key,$tablefied);
        if($table=='') return $tablefied;
        $table=env('DB_PREFIX').$table;
        if(isset($tablefied[$table])){
            return $tablefied[$table];
        }
        return [];
    }

}
